package com.example.base.app;

import com.example.base.plugin.Plugin;
import com.example.base.plugin.SystemPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class AppFunctionMap  {

    @Autowired
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    @Autowired
    private SystemPlugin systemPlugin;

    private Map<String,Map<String,AppFunction>> appMap;

    public void addFunction(String appName,String functionName,AppFunction appFunction){
        if(appMap==null){
            appMap=new HashMap<>();
        }
        Map<String,AppFunction> appFunctionMap=appMap.get(appName);
        if(appFunctionMap==null){
            appFunctionMap=new ConcurrentHashMap<>();
            appMap.put(appName,appFunctionMap);
        }
        appFunctionMap.put(functionName,appFunction);
    }

    public Map<String,AppFunction> getAppFunctionMapByAppName(String appName){
        if(appMap!=null){
            return appMap.get(appName);
        }
        return null;
    }

    @PostConstruct
    public void initSystemPlugin(){
        asyncServiceExecutor.execute(()->{
            log.info("开始添加系统插件");
            List<Plugin> pluginList=systemPlugin.getPlugin();
            String systemAppName=AppUtils.getSystemAppName();
            pluginList.forEach(e->{
                this.addFunction(systemAppName,e.getAppFunction().getAppFunctionName(),e.getAppFunction());
            });
        });
    }

}
